About 3130 letters
About 16 minutes
Modules are the basic unit of Python program organization, which organizes related code together. Simply put, a .py
file is a module.
To import a module in Python, use the import
keyword:
import module-name # Import module
from module-nam import name-list # Importing partial names from a module
For example:
import os # Import the os module, which provides operating system related interfaces
from math import pi # Import pi from the math module
print(os.name)
print(pi)
Modules mainly include file and directory:
.py
and the module name is the file name (without .py
). __init__.py
file with the module name being the directory name. When you import a directory module, you actually import the __init__.py
file in it, so you usually need to import other files in the directory in __init__.py
.
For example, the file structure is as follows:
src/ ├── main.py └── utils/ ├── __init__.py ├── helper.py └── config.py
To import directly from utils
, you need to write the following in __init__.py
:
# __init__.py
from .helper import *
from .config import *
The
.
at the beginning of the module name here refers to the current directory (the directory where the current file__init__.py
is located).*
imports all names.
For example:
# utils/__init__.py
from .helper import *
from .config import *
# utils/helper.py
def help():
print('help message')
# main.py
from utils import help # Import the help function directly without going through helper
help()
You can also import other files in the directory by import directory name.file name
(for example, import utils.helper
or from utils import helper
).
In this case, __init__.py
does not need to have any content. For example:
import utils.helper
from utils import helper
Each module has an implicit variable __name__
:
__name__
is the module name python xxx.py
), the value of __name__
is __main__
. When a module is first imported into a program, the code in it is executed.
You can use __name__
to prevent some code from being executed when it is imported, but only when it is directly run.
if __name__ == "__main__":
# code to execute
pass
Python comes with many built-in modules, called standard library modules, which can be directly imported and used without additional installation. Please refer to API Help Manual - Built-in Modules.
Python has a large number of third-party packages that can be installed through the pip
command.
pip install package-name
After installation, you can use the modules in the package.
Created in 5/15/2025
Updated in 5/21/2025